export default class Recorder {
  constructor() {
    this.stream = null;
    this.mediaRecorder = null;
    this.chunks = [];
  }

  startRecording() {
    this.chunks = []
    navigator.mediaDevices.getUserMedia({ audio: true })
      .then((stream) => {
        this.stream = stream;
        this.mediaRecorder = new MediaRecorder(stream);

        this.mediaRecorder.addEventListener('dataavailable', (event) => {
          if (event.data.size > 0) {
            this.chunks.push(event.data);
          }
        });

        this.mediaRecorder.start();
      })
      .catch((error) => {
        console.error('无法访问麦克风或用户未授权录音权限:', error);
      });
  }

  init() {
    return new Promise((resolve, reject) => {
      navigator.mediaDevices.getUserMedia({ audio: true })
        .then((stream) => {
          resolve(true)
        })
        .catch(function(error) {
          // 用户仍然拒绝录音授权或发生了错误
          uni.showToast({
            title: '无法访问麦克风，请授权录音权限',
            duration: 2000,
            icon: "none"
          });
        });
    })
  }

  stopRecording() {
    if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
      this.mediaRecorder.stop();
      this.stream.getTracks().forEach((track) => track.stop());
    }
  }
  exportRecording() {
    const blob = new Blob(this.chunks, { type: 'audio/wav' });
    return URL.createObjectURL(blob);
  }
}